<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 200px;
            height: 200px;
            background-color: #6ff;
            position: absolute;
        }
    </style>
</head>

<body>
    <div class="box"></div>
</body>
<script>
    var box = document.getElementsByClassName("box")[0];

    var clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
    var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
    var maxLeft = clientWidth - box.clientWidth;
    var maxTop = clientHeight - box.clientHeight;

    window.onresize = function () {
        clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
        clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
        maxLeft = clientWidth - box.clientWidth;
        maxTop = clientHeight - box.clientHeight;
    }

    document.onmousemove = function (e) {
        var e = e || window.event;
        var x = e.clientX - box.clientWidth / 2;
        var y = e.clientY - box.clientHeight / 2;

        if (x < 0) x = 0;
        if (y < 0) y = 0;
        if (x > maxLeft) x = maxLeft;
        if (y > maxTop) y = maxTop;

        box.style.left = x + "px";
        box.style.top = y + "px";
    }
</script>

</html>